﻿(*                  FnSharp              

   Base class library extensions and frameworks aimed 
   specifically at improving F# developers lives!

   Written by: Huw Simpson
   License: Microsoft Public License (Ms-PL) 
   Available at: http://fnsharp.codeplex.com

*)
namespace FnSharp.Bcl.Text

    open System
    open System.Text

    [<RequireQualifiedAccess>]
    [<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
    module Encoding =
        let detect (textData: byte[]) =
            if textData = null then invalidArg "textData" "Argument cannot be null!"
            
            if textData.Length < 2 then null;
            elif int (textData.[0]) = 0xff && int (textData.[1]) = 0xfe && (textData.Length < 4 || textData.[2] <> 0uy || textData.[3] <> 0uy) then Encoding.Unicode
            elif int (textData.[0]) = 0xfe && int (textData.[1]) = 0xff then Encoding.BigEndianUnicode
            elif textData.Length < 3 then null
            elif int (textData.[0]) = 0xef && int (textData.[1]) = 0xbb && int (textData.[2]) = 0xbf then Encoding.UTF8
            elif int (textData.[0]) = 0x2b && int (textData.[1]) = 0x2f && int (textData.[2]) = 0x76 then  Encoding.UTF7
            elif textData.Length < 4 then null
            elif int (textData.[0]) = 0xff && int (textData.[1]) = 0xfe && int (textData.[2]) = 0    && int (textData.[3]) = 0    then Encoding.UTF32;
            elif int (textData.[0]) = 0    && int (textData.[1]) = 0    && int (textData.[2]) = 0xfe && int (textData.[3]) = 0xff then Encoding.GetEncoding(12001);
            else null;